/**
 * 
 */
package org.vsg.common.orm.hibernate3.annotation;

import java.net.URL;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;

/**
 * @author Bill Vison
 */
public class ModuleAnnotationSessionFactoryBean extends	AnnotationSessionFactoryBean implements InitializingBean {
	
	private String domainFile = "module-domain.xml";

	
	public String getDomainFile() {
		return domainFile;
	}

	public void setDomainFile(String domainFile) {
		this.domainFile = domainFile;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		// TODO Auto-generated method stub

		ClassLoader clsLoader = this.getClass().getClassLoader();
		Enumeration<URL> enume = clsLoader.getResources(domainFile);
		Collection<Class> anno = new Vector<Class>();		
		URL url = null;
		
		SAXReader reader = new SAXReader();
		while (enume.hasMoreElements()) {
			url = enume.nextElement();
			Document doc = reader.read(url);
			parseDomains(doc , anno);
		}
		// --- release variable ---
		this.setAnnotatedClasses( anno.toArray(new Class[0]) );
		
		url = null;
		
		super.afterPropertiesSet();
		
	}
	
	// --- use dom4j ---
	private void parseDomains(Document doc , Collection<Class> anno) {
		Element rootElement = doc.getRootElement();
		
		List<Element> eles = rootElement.elements("value");

		Element elem = null;
		for (Iterator<Element> elemsIter = eles.iterator() ; elemsIter.hasNext() ; ) {
			elem = elemsIter.next();

			try {
				
				anno.add( Class.forName( elem.getText() ) );

			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	
	
	
}
